import React, { Component } from 'react'
import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {reqDeleteImg} from "../../api/index";
import PropTypes from "prop-types"
import { BASE_IMG_URL } from '../../utils/constants';

/*
    用于图片上传的组件
 */
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class PicturesWall extends Component {
    constructor(props) {
        super(props)
        let fileList =  []

        const {imgs} = this.props
        if(imgs && imgs.length > 0) {
            fileList = imgs.map((img, index) => ({
                uid: -index, //每个file都有自己唯一的uid,建议设置为负数
                name: img, // 图片文件名
                status: "done", // 图片状态: 上传已完成,uploading 正在上传中  error 错误 removed 已删除
                url: BASE_IMG_URL + img
            }))
        }
        
        this.state = {
            previewVisible: false, // 标识是否显示大图预览Modal
            previewImage: '',  // 大图的URL
            fileList, // 所有已上传图片的数组
        };
    }

    static propTypes = {
        imgs: PropTypes.array
    }
    
    
    // 获取所有已上传图片文件名的数组
    getImgs = () => {
        return this.state.fileList.map(file => file.name)
    }


    // 隐藏Modal
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
    // 显示指定file对应的大图
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
        previewImage: file.url || file.preview,
        previewVisible: true,
    });
    };
    // file: 当前操作的图片文件(上传/删除)
    // fileList: 所有已上传图片的数组
    handleChange = async ({ file, fileList }) => {
        // 一旦上传成功, 将当前上传的file的信息进行修正(name, url)
        if(file.status === "done") {
            const result = file.response
            if(result.status === 0) {
                message.success("上传图片成功!")
                const {name, url} = result.data
                file.name = name
                file.url = url
            } else {
                message.error("上传图片失败!")
            }
        } else if (file.status === "removed") { // 删除图片
            const result = await reqDeleteImg(file.name)
            if (result.status === 0) {
                message.success("删除图片成功")
            } else {
                message.error("删除图片失败")
            }
        }
        
        // 在操作(上传/ 删除)过程中更新fileList状态
        this.setState({fileList})
    };

    render() {
    const { previewVisible, previewImage, fileList} = this.state;
    const uploadButton = (
        <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div>
        <Upload
            name="image"  // 请求参数名
            accept="image/*" // 只接受图片格式	
            action="/manage/img/upload" // 上传图片的接口地址
            listType="picture-card"  // 卡片样式
            fileList={fileList} // 用来指定所有已上传图片文件对象的数组
            onPreview={this.handlePreview}
            onChange={this.handleChange}
        >
            {fileList.length >= 8 ? null : uploadButton}
        </Upload>

        <Modal
            visible={previewVisible}
            footer={null}
            onCancel={this.handleCancel}
        >
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
        </div>
    );
    }
}
